<template>
    <div class="videocontentpage">
        <van-cell>
            <template #title>
                <van-image round width="2rem" height="2rem" src="https://img01.yzcdn.cn/vant/cat.jpeg" />
                <div style="font-size: 12px; margin-left: 5px" @click="$router.push({ name: 'shopindex' })">{{ shopname }}</div>
            </template>
            <template #right-icon>
                <div class="van-cell_righticon">
                    <van-icon
                        name="search"
                        class="search-icon"
                        style="font-size: 18px; margin-right: 15px"
                        @click="$router.push({ name: 'search' })"
                    />|&nbsp;
                    <div style="font-size: 12px" @click="$router.push({ name: 'my' })">个人中心</div>
                </div>
            </template>
        </van-cell>
        <div class="prism-player" id="player-con"></div>
        <div style="height: 100px; background: white; display: flex; flex-direction: column">
            <div class="ml-10" style="font-size: 16px; font-weight: bold; margin-top: 20px">{{ item.title }}</div>
            <div class="ml-10" style="font-size: 10px; color: #aaa; margin-top: 15px">{{ item.create_time }} | {{ item.view }}次学习</div>
        </div>
        <div style="height: 5px; background: #eee" />
        <div>
            <van-tabs v-model="active">
                <van-tab title="详情">
                    <div v-html="item.custom_desc"></div>
                </van-tab>
                <van-tab title="评论">
                    <div class="mt-10 ml-10" style="width: 100vw; display: flex" v-for="(item, index) in list" :key="index">
                        <!-- <div>
                            <div><img style="width:30px; height:30px; border-radius:50% ; border: 1px solid red;" :src="item.img">
                                <span class="ml-10"  style="font-size:8px;color:#aaa">{{item.name}}</span>
                            </div>
                            <div>
                                <span style="font-size:10px;margin-left: 1rem;">{{item.text}}</span>
                            </div>
                        </div>
                        <div class="mt-10">
                            <span class="ml-10" style="font-size:8px;color:#aaa">{{item.time}}</span>
                            <a href=""  style="font-size:8px;color:#aaa;margin-left: 1rem;">回复</a>
                        </div> -->
                        <div class="box_left">
                            <img style="width: 30px; height: 30px; border-radius: 50%" :src="item.avatar" />
                        </div>
                        <div class="box_right">
                            <span class="ml-10" style="font-size: 8px; color: #aaa">{{ item.nickname }}</span>
                            <div>
                                <span style="font-size: 10px; margin-left: 0.6rem">{{ item.content }}</span>
                            </div>
                            <div class="mt-10">
                                <span class="ml-10" style="font-size: 8px; color: #aaa">{{ item.createtime }}</span>
                                <a @click="addsoncomment(item.id)" style="font-size: 8px; color: #aaa; margin-left: 1rem">回复</a>
                            </div>
                            <van-collapse v-model="activeName" accordion>
                                <van-collapse-item title="展开回复" :name="index" @click.native="getsoncomment(item.id)">
                                    <div
                                        class="mt-10 ml-10"
                                        style="width: 100vw; display: flex"
                                        v-for="(item1, index1) in sonlist"
                                        :key="index1"
                                    >
                                        <div class="box_left">
                                            <img style="width: 30px; height: 30px; border-radius: 50%" :src="item1.avatar" />
                                        </div>
                                        <div class="box_right">
                                            <span class="ml-10" style="font-size: 8px; color: #aaa">{{ item1.nickname }}</span>
                                            <div>
                                                <span style="font-size: 10px; margin-left: 0.6rem">{{ item1.content }}</span>
                                            </div>
                                            <div class="mt-10">
                                                <span class="ml-10" style="font-size: 8px; color: #aaa">{{ item1.createtime }}</span>
                                                <!-- <a href="" style="font-size:8px;color:#aaa;margin-left: 1rem;">回复</a> -->
                                            </div>
                                        </div>
                                    </div>
                                </van-collapse-item>
                                <div style="margin-bottom: 50px !important" v-if="index == list.length - 1"></div>
                            </van-collapse>
                        </div>
                    </div>
                </van-tab>
                <van-tab title="课堂评价"><xjevaluate :info_id="id" type="video"></xjevaluate></van-tab>
                <van-tab title="相关推荐"><xjtjcourse :category_id="category_id"></xjtjcourse></van-tab>
            </van-tabs>
        </div>
		
		<van-goods-action>
		    <van-goods-action-icon icon="chat-o" text="客服" color="#ee0a24" @click="gokefuchat" />
		    <van-goods-action-icon icon="cart-o" text="购物车" @click="clickshopcart" />
		    <van-goods-action-icon
		        :icon="isselect ? 'star' : 'star-o'"
		        :text="isselect ? '已收藏' : '收藏'"
		        color="#ff5000"
		        @click="clickstar"
		    />
		    <van-goods-action-button type="primary" text="免费课程" v-if="item.price == 0" />
		    <van-goods-action-button type="warning" text="你已购买" v-if="isbuyfull == 1 && item.price != 0" />
			
		    <!-- <van-goods-action-button type="warning" text="加入购物车" @click="addShopCart" v-if="isbuyfull == 0 && item.price != 0" /> -->
			<van-goods-action-button type="warning" text="加入购物车" @click="addShopCart" v-if="item.price != 0" />
		    <!-- <van-goods-action-button type="danger" text="立即购买" @click="clickbuy" v-if="isbuyfull == 0 && item.price != 0" /> -->
			<van-goods-action-button type="danger" text="立即购买" @click="clickbuy" v-if="item.price != 0" />
		</van-goods-action>
		
        <!-- <van-tabbar active-color="#000" inactive-color="#000">
            <van-tabbar-item icon="notes-o" @click="$refs.dirpopup.show = true">课程目录</van-tabbar-item>
            <van-tabbar-item icon="gift-o" @click="topresented('invite')">请好友看</van-tabbar-item>
            <van-tabbar-item icon="chat-o" @click="show = true">写评论</van-tabbar-item>
        </van-tabbar> -->
		
        <!-- 评论弹出层 -->
        <van-action-sheet v-model="show">
            <van-field v-model="message" rows="2" autosize type="textarea" maxlength="30" placeholder="请输入评论" show-word-limit>
                <template #button>
                    <van-button type="primary" size="small" class="btn" @click="comment">发表</van-button>
                </template>
            </van-field>
        </van-action-sheet>
        <xjdirpopup ref="dirpopup"></xjdirpopup>
    </div>
</template>

<script>
import xjevaluate from '@/components/frontshop/xjevaluate.vue';
import xjtjcourse from '@/components/frontshop/xjtjcourse.vue';
import xjdirpopup from '@/components/frontshop/xjdirpopup.vue';
import showfileMixin from '@/mixin/showfrontossfile.js';
import invite from './invite.vue';
export default {
    components: {
        xjevaluate,
        xjtjcourse,
        xjdirpopup,
        invite
    },
    data() {
        return {
            flag: true,
            collshow: true,
            show: false,
            shopname: localStorage.getItem('shopname') ? localStorage.getItem('shopname') : '', //店铺名
            active: 0, //默认详情
            item: '',
            id: '', //单个知识id
			type:'',
            message: '',
            list: [],
            sonlist: [],
            activeName: ['1'],
            try_time: '',
            stime: '',
            player: '',
            replyid: 0,
            category_id: '',
            leftshow: false
        };
    },
    methods: {
		
		async addShopCart() {
		    if (isWeixin()) {
		        //let rst = Cookies.get('fronttoken');
		        let logintag = sessionStorage.getItem('logintag') ? sessionStorage.getItem('logintag') : 0;
		        if (logintag == 0) {
		            //如果没有有fronttoken,则提示登录
		            sessionStorage.setItem('loginflag', 1);
		            this.$refs.xjwxreglogincom.getData();
		            return;
		        }
		    } else {
		        let rst = Cookies.get('fronttoken');
		        let htmllogintag = sessionStorage.getItem('htmllogintag') ? sessionStorage.getItem('htmllogintag') : 0;
		        if (rst == undefined || htmllogintag == 0) {
		            this.$router.push({ name: 'my' });
		            return;
		        }
		    }
		    let res = await this.$frontaxios.post(this.$front.addShopCart, { id: this.id ,type: this.type});
		    if (res.code == 1) {
		        this.$toast.success('添加购物车成功');
		    } else if (res.code == -2) {
		        this.$toast.fail('商品已加入购物车');
		    } else if (res.code == -3) {
		        this.$toast.fail('添加购物车失败');
		    } else if (res.code == -1) {
		        this.$toast.fail('你已经购买过此专栏了');
		    }
		},
		
		clickbuy() {
		    // 购买
		    if (isWeixin()) {
		        //let rst = Cookies.get('fronttoken');
		        let logintag = sessionStorage.getItem('logintag') ? sessionStorage.getItem('logintag') : 0;
		        if (logintag == 0) {
		            //如果没有有fronttoken,则提示登录
		            sessionStorage.setItem('loginflag', 1);
		            this.$refs.xjwxreglogincom.getData();
		        } else {
		            this.toOrder();
		        }
		    } else {
		        //html5浏览器
		        this.$dialog.alert({ title: '温馨提示', message: '请在微信客户端打开此页面支付购买' });
		    }
		},
		
		toOrder() {
		    let domainname = this.$route.params.domainname; //获取店铺名
		    let FrontUrl = window.location.protocol + '//' + window.location.host;
		    const nexturl = FrontUrl + `/xuejing/order/${domainname}?id=${this.id}`; //跳转到下一个页面的地址http://192.168.2.11/#/xuejing/order/test1?id=8
		    let url = this.$front.getWeiXinOpenId + `?nexturl=${encodeURIComponent(nexturl)}`; //请求获得openid并存入到服务器的Cache当中
		    window.location.href = url;
		    // this.$router.push({ name: 'order', query: { id: this.id } });
		},
		
		clickshopcart() {
		    if (isWeixin()) {
		        //let rst = Cookies.get('fronttoken');
		        let logintag = sessionStorage.getItem('logintag') ? sessionStorage.getItem('logintag') : 0;
		        if (logintag == 0) {
		            //rst == undefined||
		            //如果没有有fronttoken,则提示登录
		            sessionStorage.setItem('loginflag', 1);
		            this.$refs.xjwxreglogincom.getData();
		            return;
		        }
		    } else {
		        let rst = Cookies.get('fronttoken');
		        let htmllogintag = sessionStorage.getItem('htmllogintag') ? sessionStorage.getItem('htmllogintag') : 0;
		        if (rst == undefined || htmllogintag == 0) {
		            this.$router.push({ name: 'my' });
		            return;
		        }
		    }
		    this.$router.push({ name: 'shopcart' });
		},
		
		gokefuchat() {
		    let orderid = this.$route.query.id;
		    this.$router.push({ name: 'kefuchat', query: { orderid } });
		},
		
		async clickstar() {
		    //收藏
		    if (this.isselect == 0) {
		        this.isselect = 1;
		        let res = await this.$frontaxios.post(this.$front.addUserCollect, { columnid: this.$route.query.id });
		        if (res.code == 1) {
		            this.$toast.success('添加收藏成功');
		        } else {
		            this.$toast.fail('添加收藏失败');
		        }
		    } else {
		        this.isselect = 0;
		        let res = await this.$frontaxios.post(this.$front.delUserCollect, { columnid: this.$route.query.id });
		        if (res.code == 1) {
		            this.$toast.success('取消收藏成功');
		        } else {
		            this.$toast.fail('取消收藏失败');
		        }
		    }
		},
		
        async topresented(path) {
            const friendform = { id: this.$route.query.id, columnid: this.$route.query.columnid };
            let res = await this.$frontaxios.post(this.$front.api_doShareInfoInviteFriend, friendform);
            console.log(res);
            navigator.clipboard
                .writeText(res.data.url)
                .then(() => {
                    this.$message.success('复制成功,去发送给好友吧');
                })
                .catch((err) => {
                    this.$message.error('复制失败');
                });
        },
        addsoncomment(replyid) {
            this.show = true;
            this.replyid = replyid;
        },
        //发表评论
        async comment() {
            this.show = false;
            const obj = {
                text: this.message,
                knowledgeid: this.$route.query.id,
                replyid: this.replyid
            };
            let res = await this.$frontaxios.post(this.$front.addUserComment, obj);
            console.log(res);
            if (res.code == 1) {
                console.log(this.activeName);
                this.getcomment();
                this.getsoncomment(this.replyid);
                this.message = '';
                this.replyid = 0;
                this.$notify({ type: 'success', message: '发表成功' });
            }
        },
        //回复
        async getsoncomment(replyid) {
            this.id = this.$route.query.id;
            let res = await this.$frontaxios.post(this.$front.getUserComment, { knowledgeid: this.id, replyid });
            console.log(replyid);
            console.log(res);
            if (res.code == 1) {
                this.sonlist = res.data;
            } else {
            }
        },
        async getcomment() {
            this.id = this.$route.query.id;
            let res = await this.$frontaxios.post(this.$front.getUserComment, { knowledgeid: this.id, replyid: 0 });
            if (res.code == 1) {
                this.list = res.data;
            }
            console.log(res);
        }
    },
    mixins: [showfileMixin],
    destroyed() {
        // 销毁监听
        //this.player.dispose();
        //clearInterval(this.stime);
    },
    async mounted() {
        if (this.$route.query.key == 'invite') {
            this.$router.push({ name: 'invite', query: { id: this.$route.query.id, columnid: this.$route.query.columnid } });
        }
        this.getcomment();
        let query = {
            id: this.id,
            columnid: this.$route.query.columnid
        };
        let res0 = await this.$frontaxios.post(this.$front.getOneKnowledge, query);
        console.log(res0);
        if (res0.code == 1) {
            this.item = res0.data;
            this.category_id = res0.data.category_id;
			this.type = res0.data.type;
            let video = this.item.video;
            let path = video.path + video.name;
            let res = await this.getSignatureUrl(path);
            /* Custom events for skipping ads. These parameters are provided by the many video ad component. */
            var manyVideoAdClose = function (manyVideoAd) {
                /* Register the pause event to pause the ad. */
                manyVideoAd.pauseManyVideoAd();
                var result = confirm('确定开通会员关闭广告吗？');
                if (result) {
                    /* Register the skip event to skip the ad. */
                    manyVideoAd.closeManyVideoAd();
                } else {
                    /* Register the play event to play the ad. */
                    manyVideoAd.playManyVideoAd();
                }
            };
            let config = {
                id: 'player-con',
                source: res, //播放地址，可以是第三方点播地址，或阿里云点播服务中的播放地址。
                width: '100%',
                height: '210px',
                autoplay: true,
                isLive: false,
                rePlay: false,
                playsinline: true,
                preload: true,
                controlBarVisibility: 'hover',
                useH5Prism: true,
                // components: [{ //广告插件
                // 	name: 'ManyVideoADComponent',
                // 	type: AliPlayerComponent.ManyVideoADComponent,
                // 	args: [
                // 		[{
                // 				adVideo: 'https://alivc-demo-cms.alicdn.com/video/videoAD.mp4',
                // 				adVideoLink: 'https://www.aliyun.com/product/live'
                // 			},
                // 			{
                // 				adVideo: 'https://player.alicdn.com/resource/player/qupai.mp4',
                // 				adVideoLink: 'https://www.aliyun.com/product/live2'
                // 			},
                // 			{
                // 				adVideo: 'https://player.alicdn.com/video/guanggao.mp4',
                // 				adVideoLink: 'https://www.aliyun.com/product/live3'
                // 			}
                // 		], manyVideoAdClose, 'VIP关闭广告'
                // 	]
                // }],
                extraInfo: {
                    crossOrigin: 'anonymous'
                },
                skinLayout: [
                    {
                        name: 'bigPlayButton',
                        align: 'blabs',
                        x: 30,
                        y: 80
                    },
                    {
                        name: 'H5Loading',
                        align: 'cc'
                    },
                    {
                        name: 'errorDisplay',
                        align: 'tlabs',
                        x: 0,
                        y: 0
                    },
                    {
                        name: 'infoDisplay'
                    },
                    {
                        name: 'tooltip',
                        align: 'blabs',
                        x: 0,
                        y: 56
                    },
                    {
                        name: 'thumbnail'
                    },
                    {
                        name: 'controlBar',
                        align: 'blabs',
                        x: 0,
                        y: 0,
                        children: [
                            {
                                name: 'progress',
                                align: 'blabs',
                                x: 0,
                                y: 44
                            },
                            {
                                name: 'playButton',
                                align: 'tl',
                                x: 15,
                                y: 12
                            },
                            {
                                name: 'timeDisplay',
                                align: 'tl',
                                x: 10,
                                y: 7
                            },
                            {
                                name: 'fullScreenButton',
                                align: 'tr',
                                x: 10,
                                y: 12
                            },
                            {
                                name: 'subtitle',
                                align: 'tr',
                                x: 15,
                                y: 12
                            },
                            {
                                name: 'setting',
                                align: 'tr',
                                x: 15,
                                y: 12
                            },
                            {
                                name: 'volume',
                                align: 'tr',
                                x: 5,
                                y: 10
                            },
                            {
                                name: 'snapshot',
                                align: 'tr',
                                x: 10,
                                y: 12
                            }
                        ]
                    }
                ]
            };
            let player = new Aliplayer(config, function (player) {
                //console.log("The player is created");
                player.play();
            });
            this.player = player;

            /* h5截图按钮, 截图成功回调 */
            player.on('snapshoted', function (data) {
                var pictureData = data.paramData.base64;
                var downloadElement = document.createElement('a');
                downloadElement.setAttribute('href', pictureData);
                var fileName = 'Aliplayer' + Date.now() + '.png';
                downloadElement.setAttribute('download', fileName);
                downloadElement.click();
                pictureData = null;
            });
        } else if (res0.code == -5) {
            this.$dialog.alert({ title: '温馨提示', message: '没有查询到你兑换了课程和可能使用期限已到或没到！' }).then(() => {
                this.$router.back();
            });
            return;
        } else if (res0.code == -2) {
            this.$dialog.alert({ title: '温馨提示', message: '请购买后再来观看！' }).then(() => {
                this.$router.back();
            });
            return;
        } else if (res0.code == -1) {
            this.$dialog.alert({ title: '温馨提示', message: '没有获取到数据，请稍后再试！' }).then(() => {
                this.$router.back();
            });
            return;
        } else if (res0.code == 2) {
            //试看
            this.category_id = res0.data.category_id;
            this.try_time = res0.data.try_time;
            this.item = res0.data;
            let video = this.item.video;
            let path = video.path + video.name;
            let res = await this.getSignatureUrl(path);
            /* Custom events for skipping ads. These parameters are provided by the many video ad component. */
            var manyVideoAdClose = function (manyVideoAd) {
                /* Register the pause event to pause the ad. */
                manyVideoAd.pauseManyVideoAd();
                var result = confirm('确定开通会员关闭广告吗？');
                if (result) {
                    /* Register the skip event to skip the ad. */
                    manyVideoAd.closeManyVideoAd();
                } else {
                    /* Register the play event to play the ad. */
                    manyVideoAd.playManyVideoAd();
                }
            };
            let config = {
                id: 'player-con',
                source: res, //播放地址，可以是第三方点播地址，或阿里云点播服务中的播放地址。
                width: '100%',
                height: '210px',
                autoplay: true,
                isLive: false,
                rePlay: false,
                playsinline: true,
                preload: true,
                controlBarVisibility: 'hover',
                useH5Prism: true,
                // components: [{ //广告插件
                // 	name: 'ManyVideoADComponent',
                // 	type: AliPlayerComponent.ManyVideoADComponent,
                // 	args: [
                // 		[{
                // 				adVideo: 'https://alivc-demo-cms.alicdn.com/video/videoAD.mp4',
                // 				adVideoLink: 'https://www.aliyun.com/product/live'
                // 			},
                // 			{
                // 				adVideo: 'https://player.alicdn.com/resource/player/qupai.mp4',
                // 				adVideoLink: 'https://www.aliyun.com/product/live2'
                // 			},
                // 			{
                // 				adVideo: 'https://player.alicdn.com/video/guanggao.mp4',
                // 				adVideoLink: 'https://www.aliyun.com/product/live3'
                // 			}
                // 		], manyVideoAdClose, 'VIP关闭广告'
                // 	]
                // }],
                extraInfo: {
                    crossOrigin: 'anonymous'
                },
                skinLayout: [
                    {
                        name: 'bigPlayButton',
                        align: 'blabs',
                        x: 30,
                        y: 80
                    },
                    {
                        name: 'H5Loading',
                        align: 'cc'
                    },
                    {
                        name: 'errorDisplay',
                        align: 'tlabs',
                        x: 0,
                        y: 0
                    },
                    {
                        name: 'infoDisplay'
                    },
                    {
                        name: 'tooltip',
                        align: 'blabs',
                        x: 0,
                        y: 56
                    },
                    {
                        name: 'thumbnail'
                    },
                    {
                        name: 'controlBar',
                        align: 'blabs',
                        x: 0,
                        y: 0,
                        children: [
                            {
                                name: 'progress',
                                align: 'blabs',
                                x: 0,
                                y: 44
                            },
                            {
                                name: 'playButton',
                                align: 'tl',
                                x: 15,
                                y: 12
                            },
                            {
                                name: 'timeDisplay',
                                align: 'tl',
                                x: 10,
                                y: 7
                            },
                            {
                                name: 'fullScreenButton',
                                align: 'tr',
                                x: 10,
                                y: 12
                            },
                            {
                                name: 'subtitle',
                                align: 'tr',
                                x: 15,
                                y: 12
                            },
                            {
                                name: 'setting',
                                align: 'tr',
                                x: 15,
                                y: 12
                            },
                            {
                                name: 'volume',
                                align: 'tr',
                                x: 5,
                                y: 10
                            },
                            {
                                name: 'snapshot',
                                align: 'tr',
                                x: 10,
                                y: 12
                            }
                        ]
                    }
                ]
            };
            let player = new Aliplayer(config, (player) => {
                player.play();
                player.on('timeupdate', () => {
                    let curtime = parseInt(player.getCurrentTime());
                    console.log(this.try_time);
                    if (curtime >= this.try_time) {
                        document.querySelector('video').style.display = 'none';
                        document.querySelector('.prism-big-play-btn').style.width = '0';
                        player.dispose();
                        this.seeEnd = true;
                        this.$dialog.alert({ title: '温馨提示', message: '试看时间已经到了，请购买再来观看' }).then(() => {
                            this.$router.back();
                        });
                        // player.off('timeupdate') // 取消订阅该事件
                    }
                });
            });
            // document.querySelector('.tip-box').addEventListener('click', function () {
            //     console.log('试看结束弹窗click事件')
            // })
            this.player = player;
            /* h5截图按钮, 截图成功回调 */
            player.on('snapshoted', function (data) {
                var pictureData = data.paramData.base64;
                var downloadElement = document.createElement('a');
                downloadElement.setAttribute('href', pictureData);
                var fileName = 'Aliplayer' + Date.now() + '.png';
                downloadElement.setAttribute('download', fileName);
                downloadElement.click();
                pictureData = null;
            });
        } else {
            this.$dialog.alert({ title: '温馨提示', message: '请购买后再来观看！' }).then(() => {
                this.$router.back();
            });
        }
    }
};
</script>

<style lang="scss" scoped>
.videocontentpage {
    .van-cell__title {
        display: flex;
        flex-direction: row;
        align-items: center;
    }

    .van-cell_righticon {
        display: flex;
        flex-direction: row;
        align-items: center;
    }

    .fixvideocontent {
        position: fixed;
        right: 0;
        bottom: 0;
        left: 0;
        height: 50px;
        border-top: 1px solid #eee;
        line-height: 50px;
        display: flex;
        text-align: center;
        font-size: 12px;
    }
}

.btn {
    border-radius: 1rem;
    width: 3.5rem;
}

.van-cell__title {
    font-size: 8px;
    color: #aaa;
}
</style>
